import {app, BrowserWindow, dialog} from "electron";
import {IsUseSysTitle} from "../config/const";
import {staticPaths, winURL} from "../config/staticPath";
import DownloadFile from "../services/downloadFile";
import {otherWindowConfig} from "../config/windowsConfig";
import {IpcChannel} from "../ipc";
import {checkIsShowOnMyComputer, hideOnMyComputer, showOnMyComputer,} from "../services/regeditUtils";
import {openDevTools} from "../hook/devToolHook";

export function useMainHandle() {
	return {
		[IpcChannel.IsUseSysTitle]: () => {
			return IsUseSysTitle;
		},

		[IpcChannel.WindowMini]: (event) => {
			BrowserWindow.fromWebContents(event.sender)?.minimize();
		},
		[IpcChannel.WindowMax]: (event) => {
			if (BrowserWindow.fromWebContents(event.sender)?.isMaximized()) {
				BrowserWindow.fromWebContents(event.sender)?.restore();
				return {status: false};
			} else {
				BrowserWindow.fromWebContents(event.sender)?.maximize();
				return {status: true};
			}
		},
		[IpcChannel.WindowClose]: (event) => {
			BrowserWindow.fromWebContents(event.sender)?.close();
		},
		[IpcChannel.AppClose]: () => {
			//关闭APP前先停止内置服务器 By fm453
			// Server.StopServer();
			//
			app.quit();
		},
		[IpcChannel.GetStaticPath]: () => {
			return staticPaths;
		},
		[IpcChannel.OpenMessagebox]: async (event, arg) => {
			return dialog.showMessageBox(
				BrowserWindow.fromWebContents(event.sender),
				{
					type: arg.type || "info",
					title: arg.title || "",
					buttons: arg.buttons || [],
					message: arg.message || "",
					noLink: arg.noLink || true,
				}
			);
		},

		[IpcChannel.OpenErrorbox]: (_event, arg) => {
			dialog.showErrorBox(arg.title, arg.message);
		},

		[IpcChannel.StartDownload]: (event, downloadUrl) => {
			new DownloadFile(
				BrowserWindow.fromWebContents(event.sender),
				downloadUrl
			).start();
		},
		[IpcChannel.OpenWin]: (_event, arg) => {
			const ChildWin = new BrowserWindow({
				titleBarStyle: IsUseSysTitle ? "default" : "hidden",
				...Object.assign(otherWindowConfig, {}),
			});
			// 开发模式下自动开启devtools
			if (process.env.NODE_ENV === "development") {
				openDevTools(ChildWin);
			}
			ChildWin.loadURL(winURL + `#${arg.url}`);
			ChildWin.once("ready-to-show", () => {
				ChildWin.show();
				if (arg.IsPay) {
					// 检查支付时候自动关闭小窗口
					const testUrl = setInterval(() => {
						const Url = ChildWin.webContents.getURL();
						if (Url.includes(arg.PayUrl)) {
							ChildWin.close();
						}
					}, 1200);
					ChildWin.on("close", () => {
						clearInterval(testUrl);
					});
				}
			});
			// 渲染进程显示时触发
			ChildWin.once("show", () => {
				ChildWin.webContents.send("send-data-test", arg.sendData);
			});
		},
		[IpcChannel.CheckShowOnMyComputer]: async () => {
			return await checkIsShowOnMyComputer();
		},
		[IpcChannel.SetShowOnMyComputer]: async (event, bool) => {
			if (bool) {
				return await showOnMyComputer();
			} else {
				return await hideOnMyComputer();
			}
		},
	};
}
